package controller;

/*
 * Action for researcher menu, such as create new survey, view existing survey, etc.
 */

import helper.UserType;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import databeans.Survey;
import databeans.User;
import model.Model;
import model.Sid_RespondentDAO;
import model.SurveyDAO;
import model.UserDAO;

import org.mybeans.dao.DAOException;

public class RespondentAction extends Action {
	private Sid_RespondentDAO srDAO;
	private SurveyDAO surveyDAO;
	private UserDAO userDAO;
	
	public RespondentAction(Model model) {
		srDAO = model.getSid_RespondentDAO();
		surveyDAO = model.getSurveyDAO();
		userDAO = model.getUserDAO();
	}

	public String getName() {
		return "respondent.do";
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        // Check if user is respondent
    	HttpSession session = request.getSession(false);
    	User user = (User) session.getAttribute("user");

    	if (user.getType() != UserType.RESPONDENT) {
    		errors.add("You are not a respondent!");
    		return "homepage.jsp";
    	}
    	
    	String button = request.getParameter("button");
    	
    	if (button == null)
    		return "respondent.jsp";
    	
    	try {
        	if (button.equals("View list of surveys you can take")) {
				Survey[] surveylist = srDAO.getSurveyByResp(user.getUserid(), surveyDAO);
				session.setAttribute("surveylist", surveylist);
				return "viewsurvey.jsp";
    		}
        	
    		if (button.equals("Change password")) {
				User change_user = userDAO.lookup(user.getUserid());
				synchronized(session) {
					session.setAttribute("userchange", change_user);
					session.setAttribute("redirectto", "respondent.jsp");
				}
				return "changepassword.jsp";
    		}
    	} catch (DAOException e) {
    		errors.add(e.getMessage());
    		return "errors.jsp";
    	}

		if (button.equals("Logout")) {
			synchronized(session) {
				session.setAttribute("user", null);
			}
			return "homepage.jsp";
		}
		
		errors.add("Illegal button value of " + button);
		return "errors.jsp";
    }
}
